import 'package:aero_frisbee/app/model/af_home_user_model/af_home_user_model.dart';
import 'package:aero_frisbee/app/state/app_cache_state.dart';
import 'package:aero_frisbee/app_route.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:aero_frisbee/pages/modues/post/view_model/af_post_detail_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:go_router/go_router.dart';

import 'af_bottom_sheet_view.dart';
import 'af_pay_gift_success.dart';

class PostGiftSheetView extends ConsumerStatefulWidget {
  const PostGiftSheetView({
    Key? key,
    required this.homeUser,
  }) : super(key: key);
  final AfHomeUserModel homeUser;

  @override
  ConsumerState<PostGiftSheetView> createState() => _PostGiftSheetViewState();
}

class _PostGiftSheetViewState extends ConsumerState<PostGiftSheetView> {
  @override
  Widget build(BuildContext context) {
    final loginUserInfo = ref.watch(curlUserInfoProvider)?.userInfoModel;
    final availableCoins = loginUserInfo?.availableCoins;
    ref.listen(payForGiftServiceProvider, (previousData, newData) {
      final ret =
          newData.maybeWhen(ready: ((data) => data), orElse: () => null);
      if (ret != null && ret.item1) {
        SmartDialog.show(
          alignment: Alignment.center,
          builder: (_) => AfPayGiftSuccessContentView(successType: ret.item3),
        );
        ref
            .read(appCacheServiceProvider.notifier)
            .updateAvailableCoins(-(ret.item2));
        Future.delayed(const Duration(seconds: 3), () {
          SmartDialog.dismiss();
          Navigator.of(context).pop();
        });
      }
    });
    final isLoadding = ref.watch(payForGiftServiceProvider.select((value) {
      return value.maybeWhen(loading: () => true, orElse: () => false);
    }));

    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        return Stack(
          children: [
            AspectRatio(
              aspectRatio: 1125 / 886,
              child:
                  Assets.images.giftsSheetBg.image(width: constraints.maxWidth),
            ),
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                height: 100,
                decoration: const BoxDecoration(
                  color: Colors.white,
                ),
              ),
            ),
            Positioned.fill(
              child: Column(
                children: [
                  Stack(
                    children: [
                      AspectRatio(
                        aspectRatio: 1125 / 240,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                context.pushNamed(RouteUri.appPurchase);
                              },
                              child: Container(
                                decoration: BoxDecoration(
                                  color: const Color(0xffDDFB6C),
                                  borderRadius: BorderRadius.circular(16),
                                ),
                                margin:
                                    const EdgeInsets.only(top: 30, right: 20),
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 15, vertical: 6),
                                child: const Text(
                                  'Get coins',
                                  style: TextStyle(
                                    color: Color(0xff303507),
                                    fontWeight: FontWeight.normal,
                                    fontSize: 16,
                                  ),
                                  textAlign: TextAlign.center,
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 1,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Positioned(
                        top: 20,
                        left: 20,
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.3),
                            borderRadius: BorderRadius.circular(16),
                            border: Border.all(
                              color: const Color(0xffDDFB6C),
                              width: 0.5,
                            ),
                          ),
                          padding: const EdgeInsets.symmetric(
                              horizontal: 4, vertical: 3),
                          child: Row(
                            children: [
                              Assets.icons.iconGiftsCount.image(width: 12),
                              const SizedBox(
                                width: 8,
                              ),
                              Text(
                                ' ${availableCoins ?? 0} ',
                                style: const TextStyle(
                                  color: Color(0xff141414),
                                  fontWeight: FontWeight.normal,
                                  fontSize: 14,
                                ),
                                textAlign: TextAlign.center,
                                overflow: TextOverflow.ellipsis,
                                maxLines: 1,
                              ),
                              const SizedBox(
                                width: 2,
                              ),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                  Expanded(
                    child: Row(
                      children: [
                        const SizedBox(
                          width: 10,
                        ),
                        Expanded(
                          child: GiftContentCell(
                            type: 0,
                            onTap: isLoadding
                                ? null
                                : (count) {
                                    _onTapBuyGift(0, count);
                                  },
                          ),
                        ),
                        Expanded(
                          child: GiftContentCell(
                            type: 1,
                            onTap: isLoadding
                                ? null
                                : (count) {
                                    _onTapBuyGift(1, count);
                                  },
                          ),
                        ),
                        Expanded(
                          child: GiftContentCell(
                            type: 2,
                            onTap: isLoadding
                                ? null
                                : (count) {
                                    _onTapBuyGift(2, count);
                                  },
                          ),
                        ),
                        const SizedBox(
                          width: 10,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }

  _onTapBuyGift(int giftType, int count) {
    final loginUserInfo = ref.read(curlUserInfoProvider)?.userInfoModel;
    final availableCoins = loginUserInfo?.availableCoins;
    if ((availableCoins ?? 0) >= count) {
      ref
          .read(payForGiftServiceProvider.notifier)
          .payForGift(outlay: count, giftType: giftType);
    } else {
      context.pushNamed(RouteUri.appPurchase);
    }
  }
}

showPostGiftSheetView(BuildContext context,
    {required AfHomeUserModel homeUser}) {
  showUpBottomSheetView(
    context,
    contentColor: Colors.transparent,
    child: PostGiftSheetView(
      homeUser: homeUser,
    ),
  );
}

class GiftContentCell extends StatelessWidget {
  const GiftContentCell({
    Key? key,
    this.type = 0,
    this.onTap,
  }) : super(key: key);

  final int type;

  final Function(int count)? onTap;

  Widget get image {
    switch (type) {
      case 0:
        return Assets.icons.iconGiftsLeft.image();
      case 1:
        return Assets.icons.iconGiftsMid.image();
      default:
        return Assets.icons.iconGiftsRight.image();
    }
  }

  int get count {
    switch (type) {
      case 0:
        return 39;
      case 1:
        return 59;
      default:
        return 79;
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        onTap?.call(count);
      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          AspectRatio(
            aspectRatio: 1,
            child: image,
          ),
          const SizedBox(
            height: 16,
          ),
          Container(
            decoration: const BoxDecoration(),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Assets.icons.iconGiftsCount.image(width: 20),
                const SizedBox(
                  width: 8,
                ),
                Text(
                  '$count',
                  style: const TextStyle(
                    color: Color(0xff404040),
                    fontWeight: FontWeight.normal,
                    fontSize: 14,
                  ),
                  textAlign: TextAlign.center,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}
